/*
 * Copyright (C) 2015 Square, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xls.commonlibrary.http.gson;

import com.google.gson.TypeAdapter;
import com.xls.commonlibrary.http.ErrorCode;
import com.xls.commonlibrary.http.Result;
import com.xls.commonlibrary.http.exception.ApiException;
import com.xls.commonlibrary.http.exception.DataFormatInvalidException;
import com.xls.commonlibrary.http.exception.DataNullException;
import com.xls.commonlibrary.http.exception.TokenInvalidException;
import com.xls.commonlibrary.http.exception.TokenNotExistException;
import com.xls.commonlibrary.http.exception.VersionInvalidException;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Converter;

final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, Object> {

    private final TypeAdapter<T> adapter;

    GsonResponseBodyConverter(TypeAdapter<T> adapter) {
        this.adapter = adapter;
    }

    @Override
    public Object convert(ResponseBody value) throws IOException {
        // todo 关键所在，这里处理各种错误，eg：json格式错误等等 经典 int = "" 的问题
        try {
            Result result = (Result) adapter.fromJson(value.charStream());
            //todo custom TypeAdapter handle data=""

            if (result.getCode() == ErrorCode.TOKEN_NOT_EXIST) {
                throw new TokenNotExistException();
            } else if (result.getCode() == ErrorCode.TOKEN_INVALID) {
                throw new TokenInvalidException();
            } else if (result.getCode() == ErrorCode.VERSION_INVALID) {
                throw new VersionInvalidException();
            } else if (result.getCode() != 1) {
                // 特定 API 的错误，在相应的 Subscriber/Observer 的 onError 的方法中进行处理
                // fixme : observer能接收到吧 需确认
                throw new ApiException();
            } else if (result.getCode() == 1) {
                // 这里判断太晚了  需要在adapter.fromJson 中判断才行
//                if (result.getData() == null) {
//                    throw new DataNullException();
//                } else if ("".equals(result.getData())) {// data gson 格式错误
//
//                    throw new DataFormatInvalidException();
//                } else {
//                    return result;// 需返回整个结果对象
//                }
                return result;// 需返回整个结果对象
            }
        } finally {
            value.close();
        }
        return null;
    }
}
